package com.ruoyi.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.admin.model.response.StudentPageResp;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.admin.domain.Student;
import com.ruoyi.admin.mapper.StudentMapper;
import com.ruoyi.admin.model.request.StudentReq;
import com.ruoyi.admin.service.StudentService;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * (Student)表服务实现类
 *
 * @author makejava
 * @since 2023-03-25 14:02:33
 */
@Service("studentService")
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean add(StudentReq studentReq) {
        if (SecurityUtils.getUserType() == 1) {
            studentReq.setTeacherId(SecurityUtils.getUserId());
        }
        Student student = Student.builder()
                .studentName(studentReq.getStudentName())
                .sex(studentReq.getSex())
                .avatar(studentReq.getAvatar())
                .phonenumber(studentReq.getPhonenumber())
                .email(studentReq.getEmail())
                .password(SecurityUtils.encryptPassword(studentReq.getPassword()))
                .studentLevel(studentReq.getStudentLevel())
                .teacherId(studentReq.getTeacherId())
                .createBy(SecurityUtils.getUsername())
                .createTime(new Date())
                .status(0)
                .delFlag(0)
                .build();
        return this.save(student);
    }

    @Override
    public boolean edit(StudentReq studentReq) {
        Student studentEntity = Optional.ofNullable(this.getById(studentReq.getStudentId())).orElseThrow(() ->
                new ServiceException(StringUtils.format("未找到该studentId数据 = {}", studentReq.getStudentId()))
        );


        if (SecurityUtils.getUserType() == 1) {
            studentReq.setTeacherId(SecurityUtils.getUserId());
        }
        Student studentMode = Student.builder()
                .studentId(studentEntity.getStudentId())
                .studentName(studentReq.getStudentName())
                .sex(studentReq.getSex())
                .avatar(studentReq.getAvatar())
                .phonenumber(studentReq.getPhonenumber())
                .email(studentReq.getEmail())
                .password(SecurityUtils.encryptPassword(studentReq.getPassword()))
                .studentLevel(studentReq.getStudentLevel())
                .teacherId(studentReq.getTeacherId())
                .updateBy(SecurityUtils.getUsername())
                .updateTime(new Date())
                .build();
        return this.updateById(studentMode);
    }

    @Override
    public TableDataInfo studentPage(Page page, Student student){
        Page<Student> studentPage = this.page(page, new LambdaQueryWrapper<Student>()
                .eq(!StringUtils.equals(SecurityUtils.getUsername(), "admin"), Student::getTeacherId, SecurityUtils.getUserId())
                .eq(StringUtils.isNotEmpty(student.getStudentName()), Student::getStudentName, student.getStudentName())
        );

        List<Long> teacherIdList = studentPage.getRecords().stream().map(Student::getTeacherId).collect(Collectors.toList());

        Map<Long, String> sysUserNameMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(teacherIdList)) {
            sysUserNameMap = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                    .in(SysUser::getUserId, teacherIdList)
            ).stream().collect(Collectors.toMap(SysUser::getUserId, user -> user.getUserName()));
        }
        Map<Long, String> finalSysUserNameMap = sysUserNameMap;
        List<StudentPageResp> respList = studentPage.getRecords().stream().map(m -> {
            StudentPageResp studentPageResp = new StudentPageResp();
            BeanUtils.copyBeanProp(studentPageResp, m);
            studentPageResp.setTeacherName(finalSysUserNameMap.get(m.getTeacherId()));
            return studentPageResp;
        }).collect(Collectors.toList());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(respList);
        rspData.setTotal(studentPage.getTotal());
        return rspData;
    }
}

